package com.daJiao.handler.security;

import com.daJiao.constants.Constants;
import com.daJiao.constants.RedisKeyPrefix;
import com.daJiao.domain.WrapMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>Title:      CustomerLogoutSuccessHandler. </p>
 * <p>Description 默认的退出成功处理器 </p>
 * <p>Copyright: Copyright (c) 2016</p>
 * <p>Company:    医百科技有限公司 </p>
 *
 * @author         <a href="yangwensheng@100doc.com.cn"/>杨文生</a>
 * @Date 2021/12/07 14:45
 */
@Component("customerLogoutSuccessHandler")
public class CustomerLogoutSuccessHandler implements LogoutSuccessHandler {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException {
        String token = request.getHeader(Constants.BEARER_AUTHENTICATION);
        if (StringUtils.isNotBlank(token) && token.startsWith(Constants.BEARER_AUTHENTICATION)) {
            token = token.replace(Constants.BEARER_AUTHENTICATION, "");
            redisTemplate.delete(RedisKeyPrefix.ONLINEUSER + token);
            logger.info("退出成功,token={}",token);
        }
        SecurityContextHolder.clearContext();
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(objectMapper.writeValueAsString(WrapMapper.ok()));
    }

}
